<template>
  <div id="editor" :style="{'height': eH}"/>
</template>

<script lang="js">
import Editor from 'vditor'
import {EventsOn} from "../../wailsjs/runtime";
import {SaveFileContent} from "../../wailsjs/go/main/App";
import {defineComponent} from "vue";

export default defineComponent({
  name: "MdEditor",

  data() {
    return {
      contentEditor: undefined,
      eH: document.documentElement.clientHeight - 46 + "px",
      key: ""
    }
  },
  computed: {
    h() {
      return document.documentElement.clientHeight - 46 + "px";
    }
  },
  watch: {
    eH: {
      immediate: true,
      handler(_) {
        this.eH = document.documentElement.clientHeight - 46 + "px";
      }
    }
  },
  inject: ['eventBus'],
  mounted() {
     this.contentEditor = new Editor('editor', {
      height: document.documentElement.clientHeight - 46 + "px",
      debugger: false,
      width: '100%',
      preview: {
        hljs: {
          /** 是否启用行号。默认值: false */
          lineNumber: true,
          /** 代码风格，可选值参见 [Chroma](https://xyproto.github.io/splash/docs/longer/all.html)。 默认值: 'github' */
          style: 'github',
          /** 是否启用代码高亮。默认值: true */
          enable: true
        },
        markdown: {
          codeBlockPreview: true
        }
      },
      toolbarConfig: {
        pin: true,
      },
      tab: '    ',
      cache: {
        enable: false,
      },
      after: () => {
        this.contentEditor.setValue("");
      },
    });

    this.eH = document.documentElement.clientHeight - 46 + "px";
    window.addEventListener('resize', () => {
      this.eH = document.documentElement.clientHeight - 46 + "px";
    });

    this.eventBus.on("ReadFileContent", (fileContent) => {

      if (fileContent) {
        this.contentEditor.setValue(fileContent.value);
        this.key = fileContent.path;
      }
    });

    EventsOn("SaveFileContent", () => {
      let content = this.contentEditor.getValue();
      SaveFileContent(content, this.key).catch(e => {
        alert(e);
      });
    })

  },
});
</script>

<style>
@import 'vditor/dist/index.css';
</style>